package com.tenchael.iblog.bussiness;

import com.tenchael.iblog.domain.User;
import com.tenchael.iblog.service.UserService;
import com.tenchael.iblog.utils.BussinessChecker;
import com.tenchael.iblog.utils.MixAll;
import com.tenchael.iblog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import static com.tenchael.iblog.commons.Contants.ErrorCode.*;

/**
 * Created by tenchael on 25/12/2017.
 */
@Service
@Transactional
public class UserBussiness {

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Transactional(readOnly = true)
	public boolean login(String account, String password) {
		User findUser = userService.findByUsernameOrEmail(account, account);
		BussinessChecker.check(findUser != null,
				USER_NOT_EXIST, String.format("account(%s) is not exist", account));
		String hashedPassword = SecurityUtils.digestHexWithSha256(findUser.getSalt() + password);
		BussinessChecker.check(hashedPassword.equals(findUser.getPassword()),
				WRONG_PASSWORD, "wrong account or password");
		return true;
	}

	public User register(String username, String password, String email) {
		BussinessChecker.check(userService.findByUsername(username) != null, USER_ALREADY_EXIST,
				String.format("'%s' already exist, please use another name", username));
		BussinessChecker.check(userService.findByEmail(email) != null, USER_EMAIL_ALREADY_EXIST,
				String.format("'%s' already exist, please use another email", email));
		String salt = MixAll.hexEncode(SecurityUtils.digestWithSha256(SecurityUtils.genRandom(username.length())));
		String hashedPassword = SecurityUtils.digestHexWithSha256(salt + password);
		User user = new User(username, hashedPassword, salt, email, username, new Date());
		return userService.addUser(user);
	}
}
